package com.lznAdmin.exception;

import com.lznAdmin.base.lznAdminResult;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    // 实体校验异常捕获
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public lznAdminResult handler(MethodArgumentNotValidException e) {

        BindingResult result = e.getBindingResult();
        ObjectError objectError = result.getAllErrors().stream().findFirst().get();

        logger.error("实体校验异常：----------------{}", objectError.getDefaultMessage());
        return lznAdminResult.no(objectError.getDefaultMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public lznAdminResult handler(IllegalArgumentException e) {
        logger.error("Assert异常：----------------{}", e.getMessage());
        return lznAdminResult.no(e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = JwtException.class)
    public lznAdminResult handler(JwtException e) {
        logger.error("JWT异常：----------------{}", e.getMessage());
        return lznAdminResult.no(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public lznAdminResult handler(RuntimeException e) {
        logger.error("运行时异常：----------------{}", e.getMessage());
        return lznAdminResult.no(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = Exception.class)
    public lznAdminResult unknownException(Exception e) {
        logger.error("未知异常：----------------{}", e.getMessage());
        return lznAdminResult.no(e.getMessage());
    }

}
